<template>
  <div class="app-container">

    <!--搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单位编码" prop="measureCode">
        <el-input v-model="queryParams.measureCode" placeholder="请输入单位编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单位名称" prop="measureName">
        <el-input v-model="queryParams.measureName" placeholder="请输入单位名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:measure:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:measure:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:measure:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:measure:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="measureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单位编码" align="center" prop="measureCode" />
      <el-table-column label="单位名称" align="center" prop="measureName" />
      <el-table-column label="是否是主单位" align="center" prop="primaryFlag" />
      <el-table-column label="与主单位换算比例" align="center" prop="changeRate" />
      <el-table-column label="是否启用" align="center" prop="enableFlag" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:measure:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:measure:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增/删除按钮弹出的页面 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="单位编码" prop="measureCode">
          <el-input v-model="form.measureCode" placeholder="请输入单位编码" />
        </el-form-item>
        <el-form-item label="单位名称" prop="measureName">
          <el-input v-model="form.measureName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="是否是主单位">
          <el-radio-group v-model="form.primaryFlag" @change="changePrimaryFlag">
            <el-radio v-for="dict in dict.type.sys_y_n" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.primaryFlag == 'N'">
          <el-form-item label="主单位名称" prop="primaryName">
            <el-select v-model="form.primaryName" placeholder="请选择主单位" clearable v-loading="primaryLoading">
              <el-option v-for="item in primaryList" :key="item.measureCode" :label="item.measureName"
                :value="item.measureCode">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="换算比例" prop="changeRate">
            <el-input-number v-model="num" :precision="2" :step="0.1"></el-input-number>
          </el-form-item>
        </div>

        <el-form-item label="是否启用">
          <el-radio-group v-model="form.enableFlag">
            <el-radio v-for="dict in dict.type.sys_production_type" :key="dict.value"
              :label="dict.value">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import {
    listMeasure,
    primaryMeasure,
    addMeasure,
    updateMeasure,
    delMeasure
  } from '../../../api/maindata/unit';
  export default {
    name: "unit",
    dicts: ['sys_y_n', 'sys_production_type'],
    data() {
      return {
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          measureCode: null,
          measureName: null,
        },
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,

        // 单位表格数据
        measureList: [],

        //表单参数
        form: {},
        // 表单校验
        rules: {
          measureCode: [{
            required: true,
            message: "单位编码不能为空",
            trigger: "blur"
          }],
          measureName: [{
            required: true,
            message: "单位名称不能为空",
            trigger: "blur"
          }],
          primaryFlag: [{
            required: true,
            message: "是否是主单位不能为空",
            trigger: "blur"
          }],
          enableFlag: [{
            required: true,
            message: "是否启用不能为空",
            trigger: "blur"
          }],
        },

        //主单位列表
        primaryList: [],
        //弹出页面加载
        primaryLoading: false,
        //换算比例
        num: 1,

        ids: [], // 存储选中的measureId集合
        single: true, // 修改按钮禁用状态（选中1条时启用）
        multiple: true, // 删除按钮禁用状态（选中≥1条时启用）

      };


    },
    created() {
      this.getList()
    },
    methods: {

      /** 查询参数列表 */
      getList() {
        this.loading = true;
        listMeasure(this.queryParams).then((response) => {
          this.measureList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮 */
      handleQuery() {
        this.getList(this.queryParams).then((response) => {
          this.list = response.rows;
          this.total = response.total;
        });
      },
      /** 重置按钮 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },


      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加单位"
      },

      // 表单重置
      reset() {
        this.form = {
          measureId: undefined,
          measureCode: undefined,
          measureName: undefined,
          primaryId: undefined,
          changeRate: undefined,
          enableFlag: undefined,
          remark: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined
        }
        this.resetForm("form")
      },

      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      //查询所有主单位
      listPrimaryMeasure() {
        this.loading = true;
        return primaryMeasure().then((response) => {
            this.primaryList = response.rows;
            this.loading = false;
            return response;
          })
          .finally(() => {
            this.primaryLoading = false; // 无论成功失败，关闭加载
          });
      },
      //主单位切换事件
      changePrimaryFlag() {
        if (this.form.primaryFlag == "N") {
          //查询所有主单位
          this.listPrimaryMeasure().then((response) => {
            this.primaryList = response.data;
          });
        }
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.measureId != null) {
              updateMeasure(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addMeasure(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 修改 还没写完 */
      /*     handleUpdate(row) {
              this.reset()
              getList(row.measureId).then(response => {
                this.form = response.data
                this.open = true
                this.title = "修改单位"
                listUnitExcludeChild(row.measureId).then(response => {
                  this.measureOptions = this.handleTree(response.data, "measureId")
                  if (this.measureOptions.length == 0) {
                    const noResultsOptions = { measureId: this.form.parentId, deptName: this.form.parentName, children: [] }
                    this.measureOptions.push(noResultsOptions)
                  }
                })
              })
            }, */

      handleUpdate() {
        this.reset(); // 表单重置

        // 1. 校验：必须选中且仅选中1条数据（顶部按钮只支持单条修改）
        if (this.ids.length !== 1) {
          this.$modal.alertWarning("请选中一条数据进行修改");
          return;
        }

        // 2. 从 this.ids 中获取选中的 vendorId（this.ids 由 handleSelectionChange 收集）
        const unitId = this.ids[0];

        // 3. 调用接口获取详情，回显表单
        getUnit(unitId).then(response => {
          this.form = response.data; // 回显数据到表单
          this.open = true; // 打开修改弹窗
          this.title = "修改单位"; // 设置弹窗标题
        });
      },

      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false
        this.isExpandAll = !this.isExpandAll
        this.$nextTick(() => {
          this.refreshTable = true
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const measureIds = row.measureId || this.ids
        this.$modal.confirm('是否确认删除单位编号为"' + measureIds + '"的数据项？').then(function() {
          return delMeasure(measureIds)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },

/*      handleDelete(row) {
        // 1. 确定要删除的ID：单条删除（row存在）取row.measureId，批量删除取this.ids
        const deleteIds = row ? [row.measureId] : this.ids;

        // 2. 校验：必须选中数据
        if (deleteIds.length === 0) {
          this.$modal.alertWarning("请选中至少一条数据进行删除");
          return;
        }

        // 3. 确认删除
        this.$modal.confirm(`是否确认删除选中的 ${deleteIds.length} 条单位数据？`).then(async () => {
          // 4. 调用删除接口（若后端支持批量，可一次传数组；不支持则循环调用）
          // 这里先按“循环删除单条”处理，若后端支持批量需调整接口和代码
          for (const id of deleteIds) {
            await delMeasure(id); // 传递正确的measureId
          }
          // 5. 删除成功后刷新列表
          this.$modal.msgSuccess("删除成功");
          this.getList();
        }).catch(() => {});
      }, */
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.unitId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      }







    },
  }
</script>

<style>
</style>
